/**
 * function parentOverlayOf
 * @param el {Element}
 * @returns {ActiveOverlay | null}
 */
export const parentOverlayOf = (el) => {
    if (!el) return null;
    //closest 匹配特定选择器且离当前元素最近的祖先元素（也可以是当前元素本身）。
    // 如果匹配不到，则返回 null
    const closestOverlay = el.closest('active-overlay');
    if (closestOverlay) {
        return closestOverlay;
    }
    const rootNode = el.getRootNode();
    if (rootNode.host) {
        return parentOverlayOf(rootNode.host);
    }
    return null;
}

/**
 * @param rootOverlay {ActiveOverlay | undefined}
 * @param activeOverlays {ActiveOverlay[]}
 * @return {ActiveOverlay[]}
 */
export const findOverLaysRootedInOverlay = (rootOverlay = undefined,
                                            activeOverlays) => {
    const overlays = [];
    if(!rootOverlay) return [];
    for(const overlay of activeOverlays) {
        if(!overlay.root) continue;
        if(parentOverlayOf(overlay.root) === rootOverlay) {
            overlays.push(overlay);
            overlays.push(
                ...findOverLaysRootedInOverlay(overlay, activeOverlays)
            );
        }
    }
    return overlays;
}
